package com.lcc.lynx.base.system.excel;

import com.lcc.lynx.base.system.dict.DictCache;
import com.lcc.lynx.common.utils.PojoUtil;
import com.lcc.lynx.common.utils.ReflectUtil;
import com.lcc.lynx.common.utils.SpringUtil;
import com.lcc.lynx.common.utils.StrUtil;
import com.lcc.lynx.excel.IExcel;
import com.lcc.lynx.excel.annotation.Excel;
import jakarta.servlet.http.HttpServletRequest;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * 导出excel转换器默认实现
 * @param <T>
 */
public interface IExcelDefault<T> extends IExcel<T> {

    default T toExcel(){
        HttpServletRequest request = SpringUtil.getRequest();
        DictCache dictCache = (DictCache) request.getAttribute("_dictCache");
        T t = ReflectUtil.newInstance(this.getClass(), IExcelDefault.class, 0);
        PojoUtil.copyPropertys(this, t);
        for (Field excelField : ReflectUtil.getFields(t.getClass())) {
            Object fieldValue = ReflectUtil.getObjValue(this, excelField.getName());
            if(fieldValue == null || fieldValue instanceof Date){
                continue;
            }
            Object value = fieldValue.toString();
            if (!excelField.isAnnotationPresent(Excel.class)) {
                ReflectUtil.setFieldValue(t, excelField, value);
                continue;
            }
            Excel excel = excelField.getAnnotation(Excel.class);
            if(StrUtil.isNotEmpty(excel.dict())){
                // 字典转换
                if(dictCache == null) {
                    dictCache = new DictCache();
                    request.setAttribute("_dictCache", dictCache);
                }
                value = dictCache.getLabel(excel.dict(), fieldValue.toString());
            }
            ReflectUtil.setFieldValue(t, excelField, value);
        }
        return t;
    }
}
